package client

import java.net._
import java.io._
import scala.actors.remote._
import scala.actors.remote.RemoteActor._
import scala.actors._
import java.nio.channels._
import java.nio._
import assignments._
import messages._


/**
 * Client actor that handles communication with server.
 * @author Jacob Biggs
 * @param node	Node of the server
 */
class Connector (node : Node) extends Actor {
	
	var clientName : String = "TestClient"
	var sched : Scheduler = new Scheduler(this)
	
	/**
	 * Connects to server and sends alive message.
	 */
	def act()
	{
		// Get class loader
		RemoteActor.classLoader = getClass().getClassLoader()
		
		// Start scheduler
		sched.start()
		
		// Select remote Server Connector actor
		val serverConnector = select( this.node , Symbol("serverConnector") )
		link(serverConnector)
		
		serverConnector ! messages.toClientPool( messages.Active( InetAddress.getLocalHost(), clientName ) )
		
		loop
		{
			react
			{
				case statusMessage : StatusMessage =>
					sched forward statusMessage
					
				case assignment : Assignment =>
					sched forward assignment
					
				case requestMessage : RequestMessage =>
					requestMessage match
					{
					  case requestAssignment : RequestAssignment =>
					    serverConnector ! requestAssignment
					    
					  case x =>
					    sched forward x
					}
					
				case assignmentResult : messages.Destination =>
				  serverConnector ! assignmentResult
			}
		}
		
	}
	
	
}